package com.example.wist.mediaplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends Activity {

    static int musicNum;                           //歌曲数
    static int musicPosition=0;                    //当前播放位置
    private String TAG = "tag";
    ListView list;
    SimpleAdapter simpleAdapter;
    ArrayList<HashMap<String, Object>> Musiclist;
    static String[] artist;                         //歌手列表
    static String[] musicTitle;                     //歌名
    static String[] musicUri;                       //歌曲地址
    ImageButton startPause;                         //定义为静态是要在service里改变背景
    static SeekBar musicSeekBar;                    //进度条
    static TextView currentMTime;                   //当前播放歌曲的时间（进度）
    static TextView totalMTime;
    static TextView music;                          //播放栏的歌名
    static TextView singer;                         //播放栏的歌手
    ImageButton nextMusic;
    ImageButton prevMusic;
    boolean playState = false;
    /**
     * A-->B传数据
     * 1.A执行startActivityForResult()
     * 2.B返回setResult结果,要执行finish()结束这个activity
     * 3.A执行onActivityResult()接收B返回的结果
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //查询本地歌曲
        Intent intent = new Intent(MainActivity.this, SearchMusic.class);
        startActivityForResult(intent, 1);
        initView();                                         //初始化

        //为列表项绑定点击事件监听器
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                musicPosition  = position;//记录当前位置
                sendBroadcastToService(AppContant.PlayerMSG.MUSIC_PLAY, musicPosition);
                playState = true;
            }
        });

        //播放
        startPause.setOnClickListener(clickListener);

        //下一首
        nextMusic.setOnClickListener(clickListener);

        //上一首
        prevMusic.setOnClickListener(clickListener);

        //拖动进度条
        musicSeekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());

        //开启service
        Intent i = new Intent();
        i.setClass(MainActivity.this, MusicService.class);
        startService(i);

    }

    //初始化View
    public void initView(){

        nextMusic = (ImageButton) findViewById(R.id.btn_next_music);
        prevMusic = (ImageButton) findViewById(R.id.btn_prev_music);
        startPause = (ImageButton) findViewById(R.id.btn_start_pause);
        currentMTime = (TextView)findViewById(R.id.txt_currentTime);
        totalMTime   = (TextView)findViewById(R.id.txt_totalTime);
        //播放栏的歌名，歌手
        music = (TextView) findViewById(R.id.txt_music);
        singer= (TextView) findViewById(R.id.txt_artist);
        musicSeekBar = (SeekBar) findViewById(R.id.bar_musicBar);
        list = (ListView) findViewById(R.id.list);
    }

    //按钮监听器
    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_start_pause:              //播放暂停
                    int mResourse;
                    if(playState) {//当前状态为播放,是暂停操作
                        mResourse = R.drawable.img_button_notification_play_play_grey;
                        startPause.setBackground(getResources().getDrawable(mResourse));
                        sendBroadcastToService(AppContant.PlayerMSG.MUSIC_PAUSE, musicPosition);
                    }
                    else {
                        mResourse = R.drawable.img_button_notification_play_pause_grey;
                        startPause.setBackground(getResources().getDrawable(mResourse));
                        sendBroadcastToService(AppContant.PlayerMSG.MUSIC_PLAY, musicPosition);
                    }
                    //将播放按钮的状态取反
                    playState = !playState;
                    break;

                case R.id.btn_next_music:
                    ++musicPosition;
                    musicPosition %= musicNum;//避免取到界外
                    sendBroadcastToService(AppContant.PlayerMSG.MUSIC_PLAY, musicPosition);
                    playState = true;
                    break;

                case R.id.btn_prev_music:
                    --musicPosition;
                    musicPosition += musicNum;//避免负数取模
                    musicPosition %= musicNum;//避免取到界外
                    sendBroadcastToService(AppContant.PlayerMSG.MUSIC_PLAY, musicPosition);
                    playState = true;
                    break;
                default:
                    break;
            }
        }
    };

    //广播发送控制消息到service
    protected void sendBroadcastToService(int controlInfo, int position){
        //
        Intent intent = new Intent();
        intent.setAction(AppContant.PlayerMSG.MUSICSERVICE_ACTION);
        intent.putExtra("musicPath",musicUri[position]);
        intent.putExtra("controlInfo", controlInfo);
//        Log.e("tag",musicUri[position]);
        //向后台Service发送播放控制的广播
        sendBroadcast(intent);
    }

    //拖拉进度条
    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
            /* 用户拖动进度条 */
            if(fromUser){
                //当进度条位置改变时，播放改变的值
                MusicService.mMusicPlayer.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar){
            //开始拖动进度条时，暂停播放音乐
            MusicService.mMusicPlayer.pause();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar){
            //停止拖动进度条时，播放音乐
            MusicService.mMusicPlayer.start();
        }
    }

    /**
     * 为了得到传回的数据，必须在前面的Activity中（指MainActivity类）
     * 重写onActivityResult方法
     * <p/>
     * requestCode 请求码，即调用startActivityForResult()传递过去的值
     * resultCode 结果码，结果码用于标识返回数据来自哪个新Activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 1:
                Bundle bundle = data.getExtras();
                ArrayList a = bundle.getParcelableArrayList("result");
                Musiclist = (ArrayList<HashMap<String, Object>>) a.get(0);

                simpleAdapter = new SimpleAdapter(this, Musiclist,
                        R.layout.music_item,
                        new String[]{"musicTitle", "artist"},
                        new int[]{R.id.song, R.id.singer});

                musicNum = Musiclist.size();//获取歌曲数目
                musicTitle = new String[Musiclist.size() + 1];
                musicUri   = new String[Musiclist.size() + 1];
                artist     = new String[Musiclist.size() + 1];
                //将searchMusic返回的音乐信息装到数组里
                for (int i = 0; i < Musiclist.size(); ++i) {

                    HashMap<String, Object> musicInfo = Musiclist.get(i);
                    musicTitle[i] = (String) musicInfo.get("musicTitle");
                    artist[i]     = (String) musicInfo.get("artist");
                    musicUri[i]   = (String) musicInfo.get("musicFileUrl");
                }

                list.setAdapter(simpleAdapter);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
